import {XingHuoSocket} from "./XingHuoSocket";
import hmacSHA256 from 'crypto-js/hmac-sha256';
import Base64 from 'crypto-js/enc-base64';

export class XingHuoModel {

    constructor(options) {
        const {protocol, appId, apiKey, apiSecret, version, urlSignatureAlgorithm} = options;
        this.protocol = protocol || "ws";
        this.appId = appId;
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        this.version = version || "v3.1";
        this.urlSignatureAlgorithm = urlSignatureAlgorithm;
    }

    clearHistory() {
        const url = this.urlSignatureAlgorithm ? this.urlSignatureAlgorithm(this) : this.createUrl();
        const socket = new XingHuoSocket(url, this.appId, this.version, null);
        socket.clearHistory();
    }

    getHistory() {
        const url = this.urlSignatureAlgorithm ? this.urlSignatureAlgorithm(this) : this.createUrl();
        const socket = new XingHuoSocket(url, this.appId, this.version, null);
        return socket.getHistory();
    }

    start(seletedText, prompt, callback) {
        const url = this.urlSignatureAlgorithm ? this.urlSignatureAlgorithm(this) : this.createUrl();
        const socket = new XingHuoSocket(url, this.appId, this.version, callback);
        const text = `"${seletedText}"\n${prompt}`;
        socket.start(text);
    }

    createUrl() {
        const date = new Date().toUTCString().replace("GMT", "+0000");
        let header = "host: spark-api.xf-yun.com\n"
        header += "date: " + date + "\n"
        header += `GET /${this.version}/chat HTTP/1.1`
        const hmacSHA = hmacSHA256(header, this.apiSecret);
        const base64 = Base64.stringify(hmacSHA)
        const authorization_origin = `api_key="${this.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${base64}"`
        const authorization = btoa(authorization_origin);
        return `${this.protocol}://spark-api.xf-yun.com/${this.version}/chat?authorization=${authorization}&date=${encodeURIComponent(date)}&host=spark-api.xf-yun.com`
    }


}